package cc.cc4414.cc02.system.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cc.cc4414.cc02.core.result.ResultEnum;
import cc.cc4414.cc02.core.result.ResultException;
import cc.cc4414.cc02.system.entity.Authority;
import cc.cc4414.cc02.system.repository.AuthorityRepository;
import cc.cc4414.cc02.system.service.AuthorityService;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cc 2018年7月17日
 */
@Service
@Slf4j
public class AuthorityServiceImpl implements AuthorityService {

	@Autowired
	private AuthorityRepository authorityRepository;

	@Override
	public List<Authority> findAll() {
		return authorityRepository.findAll();
	}

	@Override
	public void save(Authority authority) {
		if (authorityRepository.findByName(authority.getName()) != null) {
			throw new ResultException(ResultEnum.AUTHORITY_EXISTED);
		}
		// id设置为空save方法才是新增，否则是修改
		authority.setId(null);
		try {
			authorityRepository.save(authority);
		} catch (Exception e) {
			log.warn("新增权限【{}】失败", authority.getDescription());
			throw new ResultException(ResultEnum.AUTHORITY_SAVE_ERROR);
		}
	}

	@Override
	public void delete(Long authorityId) {
		if (!authorityRepository.findById(authorityId).isPresent()) {
			log.warn("id为{}的权限不存在", authorityId);
			throw new ResultException(ResultEnum.AUTHORITY_NOT_EXIST);
		}
		authorityRepository.deleteRoleAuthorityByAuthorityId(authorityId);
		authorityRepository.deleteResourceAuthorityByAuthorityId(authorityId);
		authorityRepository.deleteById(authorityId);
	}

	@Override
	public void updateDescription(Long authorityId, String description) {
		Optional<Authority> optional = authorityRepository.findById(authorityId);
		if (!optional.isPresent()) {
			log.warn("id为{}的权限不存在", authorityId);
			throw new ResultException(ResultEnum.AUTHORITY_NOT_EXIST);
		}
		Authority authority = optional.get();
		authority.setDescription(description);
		authorityRepository.save(authority);
	}

	@Override
	public Authority findByName(String name) {
		return authorityRepository.findByName(name);
	}

}
